package cn.dazd.exceledit.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.dazd.exceledit.entity.FolderDto;
import cn.dazd.exceledit.service.OfficeConfig;

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
@RestController
public class FolderController {

	@Autowired
	OfficeConfig officeConfig;

	static int k;

	static synchronized int newK() {
		return ++k;
	}

	/**
	 * 获取目录下的所有文件
	 * 
	 * @param path
	 * @return
	 */

	@RequestMapping("getFolderAndFiles")
	public Object getFolderAndFiles(String path) {

		List folderList = new ArrayList(), fileList = new ArrayList();

		File rootFile = new File(officeConfig.getOfficeRoot());
		int rootLen = rootFile.getPath().length();

		File parentFile = new File(officeConfig.getOfficeRoot() + (path == null ? "/" : path.trim()));
		int parentLen = parentFile.getPath().length();
		for (File file : parentFile.listFiles()) {

			if (file.isDirectory()) {
				folderList.add(new HashMap() {
					{
						put("name", file.getName());
						put("fullPath", file.getPath().substring(parentLen).replaceAll("\\\\", "/"));
						put("isDirectory", file.isDirectory());

					}
				});
			} else {
				fileList.add(new HashMap() {
					{
						put("name", file.getName());
						put("fullPath", file.getPath().substring(rootLen).replaceAll("\\\\", "/"));
						put("isDirectory", file.isDirectory());
						put("size", file.length());

						String type = null;
						int index = file.getName().lastIndexOf(".");
						if (index > 0) {
							type = file.getName().substring(index + 1);
						}
						put("type", type);
					}
				});
			}
		}
		folderList.addAll(fileList);
		return folderList;

	}
	/**
	 * 创建目录
	 * @param json
	 * @return
	 */
	@RequestMapping("createFolder")
	public Object createFolder(@RequestBody JSONObject json ) {
		String path=json.getString("path");
		File file=new File(officeConfig.getOfficeRoot()+path);
		if (!file.exists()) {
			file.mkdirs();
		}
		return new HashMap();
	}
	/**
	 * 获取全部文件夹
	 * 
	 * @return
	 */
	@RequestMapping("getAllFolder")
	public Object getAllFolder() {

		File root = new File(officeConfig.getOfficeRoot());
		if (!root.exists()) {
			root.mkdirs();
		}

		FolderDto folderDto = new FolderDto();
		folderDto.setId(newK());
		folderDto.setLabel(officeConfig.getOfficeRoot());
		folderDto.setFullPath("");
		getFolder(root, folderDto, "");

		return new ArrayList() {
			{
				add(folderDto);

			}
		};
	}

	void getFolder(File parentFile, FolderDto parentFolder, String parentPath) {
		for (File file : parentFile.listFiles()) {
			if (file.isDirectory()) {
				FolderDto folderDto = new FolderDto();
				folderDto.setId(newK());
				folderDto.setLabel(file.getName());
				folderDto.setFullPath(parentPath + "/" + file.getName());
				parentFolder.addFolder(folderDto);

				getFolder(file, folderDto, folderDto.getFullPath());
			}

		}

	}

	/**
	 * 读取excel物理文件
	 * 
	 * @param path
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("file")
	public void file(Integer id, String path, HttpServletResponse response) throws IOException {
		if (path != null) {

			path = officeConfig.getOfficeRoot() + path;

		} else {

			// TODO 根据id查数据库
			// excelVoMapper.select
			// 这里是临时代码
			path = "C:\\Users\\Administrator\\Desktop\\工作簿1.xlsx";

		}
		String fileName = "";
		String fileType = "";
		int index = path.lastIndexOf("/");
		if (index != -1) {
			fileName = path.substring(index + 1);
		} else {
			fileName = path;
		}
		index = fileName.lastIndexOf(".");
		if (index != -1) {
			fileType = fileName.substring(index + 1);
		}

		// 打印文件
		response.reset();
		if ("xlsx".equals(fileType)) {
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
		}


		try (ServletOutputStream out = response.getOutputStream();
				FileInputStream bis = new FileInputStream(new java.io.File(path));
				BufferedOutputStream bos = new BufferedOutputStream(out);) {
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		}

	}

}
